using System;
using System.IO;
using System.Text;
using System.Xml;

namespace CosyTrade.Core
{
    public class AddinServices
    {
        public static readonly AddinServices Instance = new AddinServices();
        private readonly AddinManager addinMgr = new AddinManager();
        private AddinServices()
        {
            
        }

        public void InitalizeAddin()
        {
            XmlDocument cosyDoc = new XmlDocument();
            cosyDoc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CosyTrade.xml"));
            XmlNodeList assemlbyFile = cosyDoc.SelectNodes(@"CosyTrade/AddinAssembly");
            foreach (XmlNode node in assemlbyFile)
            {
                try
                {
                    addinMgr.LoadAddin(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, node.InnerText));
                }catch(Exception ex)
                {
                    using(StreamWriter sw =
                        new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt"), true,
                                         Encoding.UTF8))
                    {
                        sw.WriteLine(node.InnerText);
                        sw.WriteLine(ex.Message);
                        sw.WriteLine(ex.StackTrace);
                        throw;
                    }
                    
                }
            }
        }


        public void StartAddin()
        {
            foreach (IAddin addin in addinMgr.GetAddinList())
                addin.SystemInitalizeFinish();
        }

        public void Stop()
        {
            foreach (IAddin addin in addinMgr.GetAddinList())
            {
                addin.Terminate();
            }
        }


        public AddinManager AddinManager
        {
            get { return addinMgr; }
        }
    }
}